"use strict";
$(function() {
	init1();
	var hasTouch = 'ontouchstart' in window,
		//鼠标事件or触摸事件
		TAP_EV = hasTouch ? 'tap' : 'tap',
		START_EV = hasTouch ? 'touchstart' : 'mousedown',
		MOVE_EV = hasTouch ? 'touchmove' : 'mousemove',
		END_EV = hasTouch ? 'touchend' : 'mouseup';
	var onCarIndex = localStorage.getItem("onChoseCar");
	$("#onCar").attr("src","images/car0"+onCarIndex+".png");
	var game = {
		//当前桥
		currentBridge: null,
		myInterval: null,
		role: $('.role'),
		bridge: $('.bridge'),
		lineHeight: null,
		currentLevel: 0, //当前关卡
		soundStatus: false,
		bgInterval: null,
		intervalTime: 5000,
		respawn: 0,
		cutArr: ["10", "50", "80"],
		score: 0,
		//初始化
		init: function() {
			//加载完成
			$('.main').show();

			this.addEvent();

		},

		//添加事件
		addEvent: function() {
			var _this = this;
			var isClick = false;

			document.addEventListener(START_EV, banTouchScroll, false);
			var isRule = false;

			setTimeout(function() {
				_this.addDrawLineEvent();
				isClick = false;
			}, 400)
			_this.clearBgInterval();
			_this.enterPage();
			_this.createBridge();
			isClick = true;

			function banTouchScroll(event) {
				if(!isRule) {
					event.preventDefault();
				} else {

				}

			};
			$('img').on(START_EV, banTouchScroll);

		},
		reAddEvent: function() {

			var $role = this.role;
			var $bridge = this.bridge;
			var len = $bridge.find('li').length;
			for(var i = 0; i < len; i++) {
				if(i > 0) $bridge.find('li').eq(1).remove();
			};
			$role.attr('data-currentx', 0);
			this.setCss3($('.game'), 'translate(0, 0)');
			this.setCss3($role, 'none', 'none');
			$role.css('top', '-0.4rem');
			this.setCss3($bridge.find('li').first().find('.line span'), 'rotate(0deg)', 'none', {
				height: 0
			});
			var jl = -($role.width());
			this.setCss3($role, 'translate(' + jl + 'px,0)');

			var _this = this;
			var isClick = false;
			document.addEventListener(START_EV, banTouchScroll, false);
			var isRule = false;

			setTimeout(function() {
				_this.addDrawLineEvent();
				isClick = false;
			}, 400)

			this.setCss3($bridge, 'translate(0px,100%)');

			window.setTimeout(function() {
				_this.setCss3($bridge, 'translate(0,0)', 'all 0.5s');
				window.setTimeout(function() {
					$role.attr('data-currentx', 0);
					_this.setCss3($role, 'translate(0px,0)', 'all .6s linear');
				}, 500)
			}, 600)

			_this.createBridge();
			isClick = true;

			function banTouchScroll(event) {
				if(!isRule) {
					event.preventDefault();
				} else {

				}

			};
		},

		//进入页面
		enterPage: function() {
			var _this = this,
				$role = this.role,
				$bridge = this.bridge;
			this.setCss3($bridge, 'translate(0px,100%)');
			var jl = -($role.width());
			this.setCss3($role, 'translate(' + jl + 'px,0)');
			window.setTimeout(function() {
				_this.setCss3($bridge, 'translate(0,0)', 'all 0.5s');
				window.setTimeout(function() {
					$role.attr('data-currentx', 0);
					_this.setCss3($role, 'translate(0px,0)', 'all .6s linear');
				}, 500)
			}, 600)
			$('.game').show();
			$(".gameBg").show();
			this.bgAutoPlay();
		},

		//添加画线事件
		addDrawLineEvent: function() {
			var _this = this;
			$('.hit').one(START_EV, function() {
				_this.drawLineStart();
				$(this).one(END_EV, function() {
					_this.drawLineStop(function() {
						_this.advance();
					});
				})
			})
		},

		/**
		 * 下一关
		 */
		nextLevel: function() {
			var _this = this;
			this.createBridge();
			this.addDrawLineEvent();
			//当前关卡数递增
			this.currentLevel++;
		},

		/**
		 * 前进
		 */
		advance: function() {
			var _this = this,
				$role = this.role,
				$bridge = this.bridge,
				$currentBridge = this.currentBridge,
				roleCurrentX = Number($role.attr('data-currentx')),
				cx = parseInt($currentBridge.css('left'));
			cx = cx ? cx : 0;
			var $last = $bridge.find('li').last();
			var lastX = Number($last.attr('data-currentx')); //最后一个柱子的left
			//线条高度
			var lineH = this.lineHeight; //棍子的长度
			var lastW = Number($last.width()); //最后一个柱子的宽度
			var cw = Number($currentBridge.width()); //角色所站的柱子的宽度
			var spaceBetween = lastX - cx - cw;
			//是否过桥了，如果棍子的长度大于 两柱子中间的距离或棍子的长度大于柱子中间的距离+最后一个柱子的宽度，则失败
			var isPass = (lineH >= spaceBetween && lineH <= spaceBetween + lastW) ? true : false;
			var scoreBox =null;
			if((spaceBetween + lastW*0.5 - (parseInt($(".point").width()*0.5)))< lineH && lineH < (spaceBetween + lastW*0.5 + (parseInt($(".point").width()*0.5)))){
				_this.score+=3;
				scoreBox = $(".thrbox");
			}else if(isPass){
				_this.score+=1;
				scoreBox = $(".onebox")
			}
			//当前的距离，棍子的长度+角色目前站的柱子的left
			var cDistance = lineH + roleCurrentX;
			//最终距离 
			var finalDistance = lastX;
			//最后采用的距离是
			var distance = isPass ? finalDistance : cDistance + cw - $role.width();
			//运动持续时间
			var dur = (distance - cx) / 300;
			if(isPass){
				scoreBox.css({"left":lineH + cw,"bottom":6+"rem","display":"block"});
			}
			this.setCss3($role, 'translate(' + (distance) + 'px,0)', 'all ' + dur + 's linear');
			window.setTimeout(function(){
				if(scoreBox!=null){
					scoreBox.css({"left":0,"bottom":4.5+"rem","display":"none"});
					scoreBox = null;
				}
			},1500)
			//给老子走起来
			//			$role.addClass('roleRunAm');

			window.setTimeout(function() {
				//如果过桥了
				if(isPass) {
					
					//下一关
					_this.nextLevel();
					$role.attr('data-currentx', distance);
					_this.setCss3($('.game'), 'translate(' + -(distance - 20) + 'px, 0)', 'all 0.5s ease');
					$("#scoreText").text(_this.score)
				} else {
					setTimeout(function() {
						if(_this.respawn == 3) {
							$(".gameOverMask").show();
							$("#nowScore").text(_this.score);
							return;
						}
						cutArrText.innerText = _this.cutArr[_this.respawn];
						$(".mask").show();
					}, dur)

					//游戏失败
					_this.gameOver();
					//设置游戏进程
					//					_this.setTransition($role, 'all 0.2s linear');
					//					$role.css('top', $('.game').height());
					//					_this.setCss3($currentBridge.find('.line span'), 'rotate(180deg)', 'all 0.5s');
				};
				//_this.setCss3($('.game'), 'translate(-200px, 0)', 'all 0.5s ease')
			}, dur * 1000);
		},

		/**
		 * 是否还可以继续
		 */
		isContinue: function() {

		},
		isRespown: function() {
			var _this = this;
			if(_this.respawn < 3) {
				_this.respawn += 1;
				$(".mask").hide();
				_this.reAddEvent();
			} else {
				$(".gameOverMask").show();
				$("#nowScore").text(_this.score);
			}

		},
		//生成桥
		createBridge: function() {
			var _this = this,
				$role = this.role,
				$bridge = this.bridge,
				stageW = document.documentElement.clientWidth, //舞台宽
				fixW = $(".long").width(),
				$currentLevel = _this.currentLevel,
				ranW = null; //固定宽
				if (0<=$currentLevel && $currentLevel<4) {
					ranW = fixW + Math.round(Math.random()*fixW);
				} else if(4 <= $currentLevel && $currentLevel < 8){
					ranW = fixW + Math.round(Math.random()*fixW*0.8);
				}else if(8 <= $currentLevel && $currentLevel < 12){
					ranW = fixW + Math.round(Math.random()*fixW*0.6);
				}else if(12 <= $currentLevel && $currentLevel < 16){
					ranW = fixW + Math.round(Math.random()*fixW*0.4);
				}else if(16 <= $currentLevel){
					ranW = fixW + Math.round(Math.random()*fixW*0.2);
				}
			
			//获取最后一个元素
			var $lastEl = $bridge.find('li').last();
			//保存角色所站在的桥
			this.currentBridge = $lastEl;
			//最后一个元素的宽
			var lastW = $lastEl.width();

			//var lX = $lastEl.css('left');
			//随机坐标
			var ranX = Math.round((stageW - lastW - fixW - ranW - 30) * Math.random()) + (fixW + lastW) + Number($lastEl.attr('data-currentx'));
			var html = '<li class="animated slideInUp" data-currentx="' + ranX + '" style="width:' + ranW + 'px; left:' + ranX + 'px;"><div class="point"></div><div class="line"><span></span></div></li>';
			$bridge.find('ul').append(html);
		},

		bgAutoPlay: function() {
			var _this = this;
			var num = 1;
			$('.gameBg').find('.bg1,.bg2,.bg3').hide();
			if(num == 3) {
				$(".light").show();
			} else {
				$(".light").hide();
			}
			var $preBg = $('.gameBg').find('.bg' + num);
			//$preBg.css('zIndex',10);
			$preBg.show();
			this.bgInterval = window.setInterval(function() {
				num++;
				if(num == 3) {
					$(".light").show();
				} else {
					$(".light").hide();
				}
				if(!_this.bgInterval) {
					window.clearInterval(_this.bgInterval);
					return;
				}
				
				if(num > 3) num = 1;
				$preBg.fadeOut();
				$preBg = $('.gameBg').find('.bg' + num);
				$preBg.fadeIn('slow', function() {
					window.setTimeout(function() {
						for(var i = 1; i <= 3; i++) {
							if(i == num) continue;
							$('.gameBg').find('.bg' + i).fadeOut('slow');
							//$('.gameBg').find('.bg' + i).css('zIndex',0)
						};
					}, 1000)
					//$preBg.css('zIndex', 10);
				});
			}, 10000)
		},

		//画线
		drawLineStart: function() {
			var _this = this;
			var $currentBridge = this.currentBridge,
				$line = $currentBridge.find('.line'),
				$lineCon = $line.find('span');
			this.lineHeight = 0;
			this.myInterval = window.setInterval(function() {
				_this.lineHeight += 5;
				$lineCon.height(_this.lineHeight);
			}, 30)
		},

		//画线停止
		drawLineStop: function(callback) {
			var $currentBridge = this.currentBridge;
			var $lineCon = $currentBridge.find('.line span');
			if(this.myInterval) {
				window.clearInterval(this.myInterval);
				this.myInterval = null;
			}
			this.setCss3($lineCon, 'rotate(90deg)', 'all 0.4s ease')
			window.setTimeout(function() {
				if(callback) callback();
			}, 400)
		},

		//游戏数据重置
		reset: function() {
			var $role = this.role;
			var $bridge = this.bridge;
			var len = $bridge.find('li').length;
			for(var i = 0; i < len; i++) {
				if(i > 0) $bridge.find('li').eq(1).remove();
			};
			$role.attr('data-currentx', 0);
			this.setCss3($('.game'), 'translate(0, 0)');
			this.setCss3($role, 'none', 'none');
			$role.css('top', '-0.4rem');
			this.setCss3($bridge.find('li').first().find('.line span'), 'rotate(0deg)', 'none', {
				height: 0
			});
			this.addEvent();
		},

		clearBgInterval: function() {
			if(this.bgInterval) {
				window.clearInterval(this.bgInterval);
				this.bgInterval = null;
			}
		},

		//再来一次
		again: function() {
			var _this = this;
			$('.infoPage').fadeIn(500, function() {
				_this.reset();
			});
			/*this.enterPage();
			this.createBridge();
			this.addDrawLineEvent();*/
		},

		//游戏开始
		gameStart: function() {

		},

		//游戏结束
		gameOver: function() {
			//			var currentLevel = this.currentLevel;
			//			var _this = this;
			//			$('.failPanel').show();
			//			$('.failPanel').find('.backBtn').one(END_EV, function() {
			//				$('.failPanel').hide();
			//				_this.again();
			//			})
			//
			//			$('.failPanel').find('.failTxt').find('img').hide();
			//			if(currentLevel >= 3) {
			//				$('.failPanel').find('.failTxt').find('img').eq(1).show();
			//				$('.failPanel').find('.success_txt').show();
			//				$('.failPanel').find('.success_txt').text(currentLevel);
			//			} else {
			//				$('.failPanel').find('.success_txt').hide();
			//				$('.failPanel').find('.failTxt').find('img').eq(0).show();
			//			}
			//
			//			this.postGameLevel();
		},

		/**
		 * 提交游戏分数
		 */
		postGameLevel: function() {

		},

		getServerLevelData: function(callback) {

		},

		/**
		 * 获取url参数
		 * return 返回参数值
		 */
		getQueryString: function(name) {

		},

		setDur: function(obj, t, del) {

		},

		/**
		 * 设置CSS3
		 * @param {[type]} obj    [要操作的对象]
		 * @param {[type]} f      [transform]
		 * @param {[type]} t      [transition]
		 * @param {[type]} attach [其它的属性对象]
		 */
		setCss3: function(obj, f, t, attach) {
			var f = f || 'none',
				t = t || 'none';
			obj.css({
				'transform': f,
				'transition': t,
				'-webkit-transform': f,
				'-webkit-transition': t
			})
			if(attach) obj.css(attach);
		},

		//		setTransition: function(obj, t) {
		//			var t = t || 'none';
		//			obj.css({
		//				'transition': t,
		//				'-webkit-transition': t
		//			})
		//		}
	}

	//当网页加载完成
	window.onload = function() {
		game.init();
		$("#confirm").on(START_EV, function() {
			game.isRespown();
		})
		
		$("#cancel").on(START_EV,function(){
			$(this).parent().parent().hide();
			$(".gameOverMask").show();$("#nowScore").text(game.score);
		})
		
		$(".back").on(START_EV,function(){
			window.location.href="home.html";
		})
	}
})